package com.api.aiyh_pcn.fadada.web;

import aiyh.utils.ApiResult;
import aiyh.utils.LabelHtmlUtils;
import aiyh.utils.Util;
import aiyh.utils.entity.LabelHtmlIndex;
import aiyh.utils.zwl.common.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.api.aiyh_pcn.fadada.dao.FaDDContractMapping;
import com.api.aiyh_pcn.fadada.entity.UfContractInfoDTO;
import com.api.aiyh_pcn.fadada.service.impl.FaDDContractService;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.h2.util.StringUtils;
import weaver.hrm.HrmUserVarify;
import weaver.hrm.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.util.HashMap;
import java.util.Map;

/**
 * @author EBU7-dev1-ayh
 * @create 2021/11/3 0003 14:49 fadada
 */
@Path("/v2/fadada")
public class FaDDContractController {

    private final FaDDContractService faDDService = new FaDDContractService();
    private final FaDDContractMapping faDDContractMapping = new FaDDContractMapping();
    private final ToolUtil toolUtil = new ToolUtil();
    private final LabelHtmlUtils labelHtmlUtils = new LabelHtmlUtils("aiyh.htmlLabel.porsche.FaDDContractController");

    /**
     * 获取流程全版本
     *
     * @param workflowId 流程id
     * @return 流程全版本id
     */
    @Path("/getAllVersion/{workflowId}/{markOnly}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String getAllVersion(@PathParam("workflowId") String workflowId, @PathParam("markOnly") String markOnly) {
        try {
            Map<String, Object> allVersion = faDDService.getAllVersion(workflowId);
            return ApiResult.success(allVersion);
        } catch (Exception e) {
            toolUtil.writeErrorLog("错误：" + e.toString());
            return ApiResult.error(e.toString());
        }
    }

    /**
     * 合同签署回调
     *
     * @param params
     * @return
     */
    @Path("/callback/signed")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String signedCallBack(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "操作成功！");
        try {
            toolUtil.writeErrorLog("回调方法，获取到的请求参数：" + JSON.toJSONString(params));
            String resultCode = String.valueOf(params.get("resultCode"));
            if (!"1".equals(resultCode)) {
                // 签署失败
                toolUtil.writeErrorLog("合同回调：签署失败，失败信息：" + JSON.toJSONString(params));
                return JSON.toJSONString(result);
            }
            String contractNo = String.valueOf(params.get("docNo"));
            faDDService.signedCallBack(contractNo);
        } catch (Exception e) {
            toolUtil.writeErrorLog(e.toString());
        }
        return JSON.toJSONString(result);
    }

    /**
     * 是否签署完毕
     *
     * @param requestId
     * @param workflowId
     * @return
     */
    @Path("/isAllSigned/{workflowId}/{requestId}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String querySignedStatus(@PathParam("requestId") String requestId,
                                    @PathParam("workflowId") String workflowId) {
        Map<String, Object> result = faDDService.querySignedStatus(requestId);
        return ApiResult.success(result);
    }

    /**
     * 本方签署
     *
     * @param workflowId 流程id
     * @param requestId  请求id
     * @return 本方签署结果
     */
    @Path("/signedContract/own/{requestId}/{workflowId}")
    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String signedContractOwn(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                    @PathParam("workflowId") String workflowId, @PathParam("requestId") String requestId) {
        // TODO 更换labelIndex
        User user = HrmUserVarify.getUser(request, response);
        try {
            faDDService.signedContractOwn(requestId, user);
        } catch (Exception e) {
            return ApiResult.error(Util.getHtmlLabelName(-87658, user.getLanguage(), "合同签署失败！"));
        }
        return ApiResult.success(Util.getHtmlLabelName(-87657, user.getLanguage(), "本方签署成功！"));
    }

    /**
     * 催一催
     *
     * @param requestId 请求id
     * @return 催一催
     */
    @Path("/signedContract/{requestId}")
    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String signedContract(@Context HttpServletRequest request, @Context HttpServletResponse response,
                                 @PathParam("requestId") String requestId) {
        User user = HrmUserVarify.getUser(request, response);
        try {
            faDDService.pushAPush(requestId);
        } catch (Exception e) {
            LabelHtmlIndex pushErr = labelHtmlUtils.getLabelHtmlIndex("pushErr");
            toolUtil.writeDebuggerLog(e.toString());
            return ApiResult.error(Util.getHtmlLabelName(pushErr, user));
        }
        LabelHtmlIndex pushSuccess = labelHtmlUtils.getLabelHtmlIndex("pushSuccess");
        return ApiResult.success(Util.getHtmlLabelName(pushSuccess, user));
    }

    /**
     * 合同下载
     *
     * @param requestId 请求id
     * @return 合同问价压缩包
     */
    @Path("/contract/download/{requestId}")
    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response contractDownload(@PathParam("requestId") String requestId) {
        toolUtil.writeErrorLog("进入请求方法，获取到请求id：" + requestId);
        try {
            UfContractInfoDTO ufContractInfoDTO = faDDContractMapping.queryContractInfoByRequestId(requestId);
            StreamingOutput contractZipStream = faDDService.download4mFDD(ufContractInfoDTO);
            // String requestTitle =
            // Util.null2String(Util.getRequestTitleById(String.valueOf(requestId)));
            String requestTitle = ufContractInfoDTO.getFileName();
            if (StringUtils.isNullOrEmpty(requestTitle)) {
                requestTitle = "contracts.pdf";
            }
            if (Util.null2String(ufContractInfoDTO.getContractNo()).split(",").length >= 2) {
                // 多文件
                return Response.ok(contractZipStream, MediaType.APPLICATION_OCTET_STREAM).type("application/zip")
                        .header("Content-Disposition", "attachment;filename=" + requestTitle + ".zip").build();
            } else {
                // 单文件
                return Response.ok(contractZipStream, MediaType.APPLICATION_OCTET_STREAM).type("application/pdf")
                        .header("Content-Disposition", "attachment;filename=" + requestTitle).build();
            }
        } catch (Exception e) {
            toolUtil.writeErrorLog("文件流转换失败，" + e);
            return Response.ok(ApiResult.error("出现错误，错误原因: " + e), MediaType.TEXT_PLAIN).build();
        }
    }
}
